﻿using DGIS.GscloudService.IService;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace DGIS.GscloudService.Service
{
    public class HttpService : IHttpService
    {
        public string GetHttpWebPostResult(string url, string postDataStr, ref CookieContainer cookieContainer)
        {
            try
            {
                Uri uri = new Uri(url);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.CookieContainer = cookieContainer;//设置cookie
                request.Accept = "Accept:application/json, text/javascript, */*; q=0.01";
                request.Method = "POST";//POST 提交
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";//以上信息在监听请求的时候都有的直接复制过来

                //提交请求  
                byte[] bytes = Encoding.UTF8.GetBytes(postDataStr);
                request.ContentLength = bytes.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();//POST数据写入

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (cookieContainer != null)
                    SetCookies(uri, response.Cookies, ref cookieContainer);
                Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader myreader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string result = myreader.ReadToEnd();
                responseStream.Close();
                myreader.Close();

                request.Abort();
                response.Close();

                return result;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "";
            }
        }

        public string GetHttpWebPostResult(string url, string postDataStr, Dictionary<string, string> headersDic,  ref CookieContainer cookieContainer)
        {
            try
            {
                Uri uri = new Uri(url);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";//POST 提交
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";//以上信息在监听请求的时候都有的直接复制过来

                foreach (KeyValuePair<string, string> header in headersDic)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
                request.CookieContainer = cookieContainer;//设置cookie

                //提交请求  
                byte[] bytes = Encoding.UTF8.GetBytes(postDataStr);
                request.ContentLength = bytes.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();//POST数据写入

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                SetCookies(uri, response.Cookies, ref cookieContainer);
                Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader myreader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string result = myreader.ReadToEnd();
                responseStream.Close();
                myreader.Close();

                request.Abort();
                response.Close();

                return result;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "";
            }
        }

        public string GetHttpWebGetReuslt(string url, ref CookieContainer cookieContainer)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";//以上信息在监听请求的时候都有的直接复制过来
                request.CookieContainer = cookieContainer;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.Cookies != null)
                    cookieContainer.Add(response.Cookies);
                Stream stream = response.GetResponseStream();
                System.IO.StreamReader myreader = new System.IO.StreamReader(stream, Encoding.UTF8);
                string result = myreader.ReadToEnd();
                myreader.Close();

                request.Abort();
                response.Close();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "";
            }
        }

        public string GetHttpWebGetReuslt(string url, Dictionary<string, string> headersDic, ref CookieContainer cookieContainer)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";//以上信息在监听请求的时候都有的直接复制过来

                foreach (KeyValuePair<string, string> header in headersDic)
                {
                    request.Headers.Add(header.Key, header.Value);
                }

                request.CookieContainer = cookieContainer;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.Cookies != null)
                    cookieContainer.Add(response.Cookies);
                Stream stream = response.GetResponseStream();
                System.IO.StreamReader myreader = new System.IO.StreamReader(stream, Encoding.UTF8);
                string result = myreader.ReadToEnd();
                myreader.Close();

                request.Abort();
                response.Close();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "";
            }
        }

        public string GetHttpWebResponseUrl(string url, ref CookieContainer cookieContainer)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";//以上信息在监听请求的时候都有的直接复制过来
                request.CookieContainer = cookieContainer;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string responseUrl = response.ResponseUri.AbsoluteUri;

                request.Abort();
                response.Close();

                return responseUrl;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return "";
            }
        }

        private void SetCookies(Uri uri, CookieCollection cookies, ref CookieContainer cookieContainer)
        {
            CookieCollection cookieCollection = cookieContainer.GetCookies(uri);
            for (int i = 0; i < cookies.Count; i++)
            {
                Cookie cookie = cookies[i];
                if (cookieCollection[cookie.Name] != null)
                {
                    if (!string.IsNullOrEmpty(cookie.Value))
                        cookieCollection[cookie.Name].Value = cookie.Value;
                }
                else
                {
                    cookieContainer.Add(new Cookie(cookie.Name, cookie.Value, "/", uri.Host));
                }
            }

        }

        public bool DownloadImg(string url, string savePath, ref CookieContainer cookieContainer)
        {
            Stream stream = GetHttpWebGetImg(url, ref cookieContainer);
            Bitmap img = new Bitmap(stream);
            if (img != null)
            {
                img.Save(savePath);
                img.Dispose();
                return true;
            }
            return false;
        }

        public Stream GetHttpWebGetImg(string url, ref CookieContainer cookieContainer)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.CookieContainer = cookieContainer;
                //request.Headers.Add("Host:booknow.jetstar.com;Origin: http://booknow.jetstar.com;Referer: http://booknow.jetstar.com/Select.aspx;Upgrade - Insecure - Requests:1");

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //response.Headers.Add("Cache-Control:no-cache, no-store;Connection: keep - alive;Content - Encoding:gzip;Content - Length:31082;Content - Type:text / html; charset = utf - 8;Date: Thu, 10 Mar 2016 08:16:43 GMT; Expires:-1;Pragma: no - cache;Set - Cookie:sessionculture = en - AU; domain =.jetstar.com; expires = Fri, 11 - Mar - 2016 08:16:42 GMT; path =/;Vary:Accept - Encoding;X - AspNet - Version:2.0.50727;X - Powered - By:ASP.NET");
                cookieContainer.Add(response.Cookies);

                Stream stream = response.GetResponseStream();

                MemoryStream memoryStream = new MemoryStream();
                stream.CopyTo(memoryStream);

                //Bitmap bitmap = new Bitmap(stream);

                request.Abort();
                response.Close();

                return memoryStream;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}
